package com.hoyue.system.controller;

import com.hoyue.common.utils.ShiroUtils;
import com.hoyue.system.bean.Role;
import com.hoyue.system.bean.User;
import com.hoyue.system.service.RoleService;
import com.hoyue.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Set;

/**
 * @author 空白
 * @version 1.0
 * Create by 2019/08/10 17:41
 */
@Controller
@RequestMapping("/user")
public class UserController {

    private String prefix = "personal";

    @Autowired
    UserService userService;

    @Autowired
    RoleService roleService;

    /**
     * 注册用户
     * @param roleId
     * @param user
     * @return redirect:/login
     * @throws Exception
     */
    @PostMapping("/register")
    public String register(@RequestParam("customRadioInline") int roleId, User user) {
        // 将用户基本信息写入到sys_user表中
        int userId = userService.insertUser(user);
        // 将用户id和角色id进行关联
        roleService.insertRole(userId, roleId);
        return "redirect:/login";
    }

    /**
     * 跳转到个人页面
     * @return
     */
    @GetMapping("personal")
    public String personal(Model model) {
        //查询当前用户信息
        User user = ShiroUtils.getUser();
        if (user == null) {
            // 如果缓存中未找到，则从数据库中取出
            user = userService.getLoginUser();
        }
        // 查询当前用户拥有的角色
        Set<Role> roles = ShiroUtils.getRoles();
        if (roles == null) {
            // 如果缓存中未找到，则从数据库中取出
            roles = roleService.getRoles(user.getId());
        }
        model.addAttribute("user", user);
        model.addAttribute("roles", roles);
        return prefix + "/personal";
    }

}
